package com.meixiang.activity.moments;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.moments.ReplyDetailsAdapter;
import com.meixiang.entity.moments.ReplyDetailBean;
import com.meixiang.entity.moments.ReplyDetailList;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：黑哥 on 2016/5/7 10:53
 * <p/>
 * 评论详情
 */
public class ReplyDetailsActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.swipe_target)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.et_input_dialog_box)
    ClearEditText mEtInputDialogBox;
    @Bind(R.id.tv_send_message)
    TextView mTvSendMessage;
    private Activity mActivity;

    private String commentId;

    private ReplyDetailsAdapter mAdapter;


    private ReplyDetailBean mBean;
    private List<ReplyDetailList> mList=new ArrayList<>();
    private int pageNo = 1, pageSize = 10, totalPage = 0;

    private boolean isRefresh = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_reply_details);
        mActivity = ReplyDetailsActivity.this;
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("评论详情");
    }

    @Override
    protected void initView() {
        mTvSendMessage.setOnClickListener(this);

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new ReplyDetailsAdapter(mActivity);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new ReplyDetailsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                autoPopupKeyboard();
            }
        });
        /**检查RecyclerView是否滑动底部如果滑到*/
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });

    }

    @Override
    protected void setData() {
        if(getIntent().getExtras().getString("commentId")!=null){
            commentId=getIntent().getExtras().getString("commentId");
        }
        status.showLoading();
        getDetailedData(1,true);
    }
    public void getDetailedData(int pageNo, final boolean isPull){
        HttpParams params = new HttpParams();
        params.put("pageSize", pageSize + "");
        params.put("pageNo", pageNo + "");
        params.put("commentId",commentId);
        HttpUtils.post(Config.MOMENTS_MORE_COMMENT, params, new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isPull){
                    mAdapter.clear();
                }
                mBean= AbJsonUtil.fromJson(result.toString(),ReplyDetailBean.class);
                mList=mBean.getReplyDetaiList();
                if (mList==null||mList.size()==0){
                    status.showNoData("暂无数据");
                }else{
                    status.removeView();
                    mAdapter.addAll(mList);
                }
            }
            @Override
            public void onError(String code, String message) {
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getDetailedData(1, true);
                    }
                });
                AbToastUtil.showToast(context,message);
            }


            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onCompleteRefresh();
            }
        });
    }
    private void doSendMessage() {
        /**
         *replyMemberId 评论id
         *commentId   回复id
         *comment   评论内容
         * */
        HttpParams params = new HttpParams();
        params.put("replyMemberId","");
        params.put("commentId",commentId);
        params.put("comment",mEtInputDialogBox.getText().toString());
        HttpUtils.post(Config.MOMENTS_COMMENT_EDIT, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                /**取消获取焦点  清空数据*/
                mEtInputDialogBox.clearFocus();
                mEtInputDialogBox.setInputType(InputType.TYPE_NULL);
                mEtInputDialogBox.setText("");
                Tool.showTextToast(context,message);
                /**刷新列表数据*/
                onRefresh();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);

            }
        });



    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send_message:
                doSendMessage();
                break;
        }



    }

    private void onCompleteRefresh() {
        if (mRefresh != null) {
            if (isRefresh == true) {
                mRefresh.setRefreshing(false);
            } else {
                mRefresh.setLoadingMore(false);
            }
        }
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (mBean.pageNo<mBean.totalPage){
            int  pageNo=mBean.pageNo+1;
            getDetailedData(pageNo,false);
        }else{
            AbToastUtil.showToast(activity,"已无更多内容");
            mRefresh.setLoadingMore(false);
        }

    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        getDetailedData(1,true);
    }

    /**
     *
     * 自动获取editext焦点
     * 弹出键盘
     *
     * */
    public void autoPopupKeyboard(){
        mEtInputDialogBox.requestFocus();//获得焦点
        InputMethodManager mInputMethodManager= (InputMethodManager) mEtInputDialogBox.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        mInputMethodManager.toggleSoftInput(0,InputMethodManager.SHOW_FORCED);
    }

}
